package com.inspur.edp.formserver.vmmanager.i18nservice;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.cef.designtime.api.i18n.context.CefResourceExtractContext;
import com.inspur.edp.cef.designtime.api.i18n.context.CefResourceMergeContext;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.i18n.ViewModelResourceExtractor;
import com.inspur.edp.formserver.viewmodel.i18n.merger.ViewModelResourceMerger;
import com.inspur.edp.lcm.metadata.api.entity.*;
import com.inspur.edp.lcm.metadata.spi.MetadataI18nService;

public class ViewModelI18nService implements MetadataI18nService {
    public GspMetadata merge(GspMetadata metadata, java.util.List<I18nResource> list) {

        if (list==null || list.size()==0)
            return metadata;
        if (!(metadata.getContent() instanceof GspViewModel))
            return  metadata;
        I18nResourceItemCollection resourceItems=list.get(0).getStringResources();
        if (resourceItems==null)
            return metadata;
        GspViewModel viewModel= (GspViewModel) metadata.getContent();
        mergeViewModelResource(viewModel,resourceItems);

        metadata.setContent(viewModel);
        return metadata;
    }

    private void mergeViewModelResource(GspViewModel viewModel,
        I18nResourceItemCollection resourceItems) {
        CefResourceMergeContext context=new CefResourceMergeContext(viewModel.getDotnetGeneratingAssembly(),resourceItems);
        ViewModelResourceMerger merger=new ViewModelResourceMerger(viewModel,context);
        merger.merge();
    }

    public I18nResource getResourceItem(GspMetadata metadata) {
        I18nResource resource = new I18nResource();
        resource.setResourceType(ResourceType.Metadata);
        resource.setResourceLocation(ResourceLocation.Backend);
        GspViewModel vo = (GspViewModel) metadata.getContent();
        String assemblyName = vo.getDotnetGeneratingAssembly();
        I18nResourceItemCollection collection = new I18nResourceItemCollection();
        extractBizEntityI18nResource(vo, assemblyName, collection);

        resource.setStringResources(collection);
        return resource;

    }

    private void extractBizEntityI18nResource(GspViewModel vo, String metaNamespace, I18nResourceItemCollection items) {
        CefResourceExtractContext context = new CefResourceExtractContext(metaNamespace, items);
        ViewModelResourceExtractor extractor = new ViewModelResourceExtractor(vo, context);
        extractor.extract();
    }
}
